package com.iweb.server;

import com.alibaba.fastjson.JSON;
import com.iweb.pojo.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint("/imOne/{userId}")  // 请求的url
@Component
public class WebOneToOneServer {

    // 线程安全的 用来存放每个客户端对应的 Session 单机可以这么做，集群的情况下需要 mysql 或者 redis 改造 sendMessage 方法
    private static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接成功后调用的方法
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void open(Session session, @PathParam("userId") String userId) {
        log.info("{}连接了", userId);
        clients.put(userId, session);
        log.info("在线人数:{}", clients.size());
    }

    /**
     * 断开连接
     *
     * @param session
     * @param userId
     */
    @OnClose
    public void close(Session session, @PathParam("userId") String userId) {
        log.info("{}断开了", userId);
        clients.remove(userId);
    }

    /**
     * 发生异常调用
     *
     * @param t
     */
    @OnError
    public void error(Throwable t) {
        t.printStackTrace();
    }

    @OnMessage
    public void message(String message, @PathParam("userId") String userId) throws IOException {
        log.info("服务器接收到{}发送的消息：{}", userId, message);
        Message m = JSON.parseObject(message, Message.class);
        sendTo(m, userId);
    }

    private void sendTo(Message message, String userId) throws IOException {
        Session session = clients.get(message.getUserId());
        assert session != null;
        session.getBasicRemote().sendText(userId + "说：" + message.getMessage());
    }

}
